from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pathlib import Path
from datetime import datetime


class BasePage:
    TIMEOUT = 10
    POLL_FREQUENCY = 0.5

    def __init__(self, driver):

        self.driver = driver
        self.wait = WebDriverWait(driver, self.TIMEOUT, self.POLL_FREQUENCY)

    def find_element(self, locator, timeout=None):
        wait = (
            self.wait
            if timeout is None
            else WebDriverWait(self.driver, self.TIMEOUT, self.POLL_FREQUENCY)
        )
        try:
            return wait.until(EC.presence_of_element_located(locator))
        except Exception as e:
            on_time = datetime.now().strftime('%Y%m%d%H%M%S')
            by_, *_ = locator
            self.taka_screenshot(f'element_not_found_{on_time}_{by_}.png')

    def taka_screenshot(self, name):
        sh = self.driver.get_screenshot_as_png()
        file_path = Path(__file__).parent.parent.parent / "outputs/screenshots"
        full_file_name = file_path / f"{name}.png"
        with open(full_file_name, "wb") as f:
            f.write(sh)
